package com.kgcx.price.service;

import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.client.organization.CarClient;
import com.kgcx.common.client.organization.pojo.Auto;
import com.kgcx.price.domain.MileageRecord;
import com.kgcx.price.mapper.MileageRecordMapper;
import com.kgcx.price.rabbitmq.BaseInfoProducer;
import com.kgcx.price.utils.SystemVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class MileageRecordService {
    @Autowired
    MileageRecordMapper mileageRecordMapper;

    @Autowired
    BaseInfoProducer baseInfoProducer;

    @Autowired
    CarClient carClient;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * recordStartMile 记录司机上传开始里程
     *
     * @param mileageRecord 里程记录表
     * @return ReturnData
     */
    public ReturnData<MileageRecord> recordStartMile(MileageRecord mileageRecord) {
        if (StringUtils.isEmpty(mileageRecord.getCarId())) {
            return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "车辆信息为空");
        }

        if (StringUtils.isEmpty(mileageRecord.getOrderId())) {
            return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "订单信息为空");
        }

        if (StringUtils.isEmpty(mileageRecord.getStartMileage())) {
            return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "开始里程为空");
        }

        if (!StringUtils.isEmpty(mileageRecord.getEndMileage())) {
            return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "结束里程不为空");
        }

        try {
            /** 根据车辆Id取得车辆历史行程信息 */
            MileageRecord mileageRecordRetrun = mileageRecordMapper.selectByCarId(mileageRecord);

            /** 进制转换，系统统一用基本计量单位，公里换算成米 */
            Long startMileageToMeter = mileageRecord.getStartMileage() * 1000;

            /** 如果历史行程为空，则直接入库 */
            if (mileageRecordRetrun == null || mileageRecordRetrun.getStartMileage() == null || mileageRecordRetrun.getEndMileage() == null) {
                mileageRecord.setStartMileage(startMileageToMeter);

                if (mileageRecordMapper.insertSelective(mileageRecord) > 0) {
                    return new ReturnData<>(mileageRecord, SystemVariable.SUCCESS_RETURN_CODE, "上传开始里程成功");
                } else {
                    return new ReturnData<>(mileageRecord, SystemVariable.ERROR_RETURN_CODE, "上传开始里程失败");
                }
            } else {
                /** 否则判断输入的开始里程是否大于之前的结束里程，大于则直接入库，不大于入库驳回 */
                /** 有坑：如果开始里程可以重复上传 mileageRecordRetrun.getEndMileage() 会报空指针错，需注意 */
                if (mileageRecordRetrun.getEndMileage() > startMileageToMeter) {
                    return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "开始里程小于历史行程，请按车辆里程表输入正确开始里程");
                } else {
                    mileageRecord.setStartMileage(startMileageToMeter);

                    if (mileageRecordRetrun.getOrderId().equals(mileageRecord.getOrderId())) {
                        return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "订单号与历史订单号重复！");
                    }

                    if (mileageRecordMapper.insertSelective(mileageRecord) > 0) {
                        return new ReturnData<>(mileageRecord, SystemVariable.SUCCESS_RETURN_CODE, "上传开始里程成功");
                    } else {
                        return new ReturnData<>(mileageRecord, SystemVariable.ERROR_RETURN_CODE, "上传开始里程失败");
                    }
                }
            }
        } catch (Exception e) {
            logger.error("上传里程异常", e);
            return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "上传里程异常:" + e.getMessage());
        }
    }

    /**
     * recordEndMile 记录司机上传结束里程
     *
     * @param mileageRecord 里程记录表
     * @return ReturnData
     */
    public ReturnData<MileageRecord> recordEndMile(MileageRecord mileageRecord) {
        if (StringUtils.isEmpty(mileageRecord.getEndMileage())) {
            return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "结束里程为空");
        }

        if (StringUtils.isEmpty(mileageRecord.getKid())) {
            return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "标识符为空");
        }

        try {
            /** 根据车辆Id取得车辆历史行程信息 */
            MileageRecord mileageRecordRetrun = mileageRecordMapper.selectByPrimaryKey(mileageRecord.getKid());

            if (mileageRecordRetrun == null) {
                mileageRecordRetrun = mileageRecordMapper.selectByOrderId(mileageRecord);
            }

            if (mileageRecordRetrun == null) {
                return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "根据标识符未查询到相关信息");
            } else {
                Long startMileage = mileageRecordRetrun.getStartMileage();
                /** 单位进制换算 */
                Long endMileage = mileageRecord.getEndMileage() * 1000;

                if (startMileage > endMileage) {
                    return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "结束里程小于开始里程");
                }

                /** 行程不能超过500公里 */
                if ((endMileage - startMileage) > 500000) {
                    return new ReturnData<>(SystemVariable.ERROR_RETURN_CODE, "行程过远");
                }

                MileageRecord mileageRecordDB = new MileageRecord();

                mileageRecordDB.setEndMileage(endMileage);

                if (mileageRecord.getKid() == 0 || mileageRecord.getKid() == null) {
                    mileageRecordDB.setKid(mileageRecordRetrun.getKid());
                } else {
                    mileageRecordDB.setKid(mileageRecord.getKid());
                }

                if (mileageRecordMapper.updateByPrimaryKeySelective(mileageRecordDB) > 0) {
                    /** 拼装给监管平台对象 */
                    try {
                        Auto auto = carClient.getAuto(Long.valueOf(mileageRecordRetrun.getCarId()));

                        MileageRecord mileageRecordJG = new MileageRecord();

                        mileageRecordJG.setAddress(auto.getCityId());
                        mileageRecordJG.setVehicleNo(auto.getAutoNo());
                        mileageRecordJG.setTatalMile(mileageRecord.getEndMileage() * 1000);
                        //                    mileageRecordJG.setCreateTime(new Timestamp(System.currentTimeMillis()));

                        logger.warn("" + mileageRecordJG);
                        /** 发mq消息给监管平台接口 */
                        baseInfoProducer.addBaseInfoCarDistance(mileageRecordJG);

                        return new ReturnData<>(mileageRecord, SystemVariable.SUCCESS_RETURN_CODE, "上传结束里程成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getMessage());
                        return new ReturnData<>(mileageRecord, SystemVariable.SUCCESS_RETURN_CODE, "上传结束里程成功");
                    }
                } else {
                    return new ReturnData<>(mileageRecord, SystemVariable.ERROR_RETURN_CODE, "上传结束里程失败");
                }
            }
        } catch (Exception e) {
            logger.error("上传里程异常", e);
            return new ReturnData<>(SystemVariable.SUCCESS_RETURN_CODE, "上传里程异常:" + e.getMessage());
        }
    }
}
